package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.FocusUser;
import com.itheima.domain.mongo.Video;
import com.itheima.domain.vo.CommentVo;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.domain.vo.VideoVo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.FocusUserService;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.DateFormatUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class VideoManager {
    @Reference
    private VideoService videoService;

    @Reference
    private UserInfoService userInfoService;

    @Reference
    private CommentService commentService;

    @Autowired
    private MQVideoManager mqVideoManager;

    /**
     * 查询小视频的列表
     * @param page
     * @param pageSize
     * @return
     */
    //@Cacheable(value = "tanhua" , key = "'video_'+#page+'_'+#pageSize")
    public PageBeanVo findSmallVideos(Integer page, Integer pageSize) {
        //1.获得当前用户id
        Long loginUserId = UserHolder.getId();
        //2.调用service查询pageBean信息
        PageBeanVo pageBeanVo = videoService.findSmallVideos(page, pageSize, loginUserId);
        List<Video> videoList = (List<Video>) pageBeanVo.getItems();

        List<VideoVo> voList = new ArrayList<>();

        if(CollectionUtil.isNotEmpty( videoList )){
            for (Video video : videoList) {
                //3.查询用户的信息
                UserInfo userInfo = userInfoService.findById(video.getUserId());
                //4.封装vo对象
                VideoVo vo = new VideoVo();
                //4.1 赋值匹配成功的数据
                BeanUtil.copyProperties( userInfo , vo );
                BeanUtil.copyProperties( video , vo );

                //4.2 赋值不成功的数据
                //vo.setUserId();
                vo.setCover( video.getPicUrl() ); //封面
                vo.setVideoUrl( video.getVideoUrl() );//视频
                vo.setSignature("左手右手一个慢动作");//只能写死 发布视频的文字
                vo.setHasLiked(0);//是否点赞

                String key = StrUtil.format(ConstantUtil.FOCUS_USER ,UserHolder.getId() , video.getUserId()  );
                if(stringRedisTemplate.hasKey(key)){
                    vo.setHasFocus(1);//是否关注
                }else{
                    vo.setHasFocus(0);//是否关注
                }

                //

                voList.add(vo);
            }
        }
        pageBeanVo.setItems(voList);
        //5.返回
        return pageBeanVo;
    }

    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private FdfsWebServer webServer; //上传的服务器 此处红线是idea编译器的问题 能正常使用
    @Autowired
    private FastFileStorageClient client; // 使用的客户端  此处红线是idea编译器的问题 能正常使用


    /**
     * 保存视频
     * @param videoThumbnail
     * @param videoFile
     * @return
     */
    //@CacheEvict(value = "tanhua" , allEntries = true)  // allEntries = true 删除所有的内容缓存
    public Map saveSmallVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //1.构建video
        Video video = new Video();
        video.setUserId( UserHolder.getId() );
        video.setText("左手右手一个慢动作");

        //上传封面
        if(videoThumbnail!=null && videoThumbnail.getSize()>0){
            String upload =  ossTemplate.upload(System.currentTimeMillis() + videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
            video.setPicUrl("https://"+upload);//封面
        }

        //上传视频
        if(videoFile!=null && videoFile.getSize()>0){

            StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), FileUtil.extName(videoFile.getOriginalFilename()), null);

            video.setVideoUrl(webServer.getWebServerUrl() + storePath.getFullPath());//视频
        }


        //2.保存
        videoService.save(video);
        return null;
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Reference
    private FocusUserService focusUserService;
    //关注
    //@CacheEvict(value = "tanhua" , allEntries = true)  // allEntries = true 删除所有的内容缓存
    public Map saveUserFocus(Long videoUserId) {
        //1.创建对象
        FocusUser focusUser = new FocusUser();
        //2.保存对象
        focusUser.setUserId( UserHolder.getId() );
        focusUser.setFocusUserId(videoUserId);

        focusUserService.save(focusUser);
        //3.放入缓存
        String key = StrUtil.format(ConstantUtil.FOCUS_USER ,UserHolder.getId() , videoUserId  );
        stringRedisTemplate.opsForValue().set(key , "1");
        return null;
    }

    //取消关注
    //@CacheEvict(value = "tanhua" , allEntries = true)  // allEntries = true 删除所有的内容缓存
    public Map removeUserUnFocus(Long videoUserId) {
        //删除关注
        focusUserService.remove(UserHolder.getId() , videoUserId);
        String key = StrUtil.format(ConstantUtil.FOCUS_USER ,UserHolder.getId() , videoUserId  );
        //删除缓存
        stringRedisTemplate.delete(key);
        return null;
    }

    //小视频点赞
    public Integer likeVideo(String videoUserId) {

        //创建对象
        Comment comment=new Comment();
        comment.setPublishId(new ObjectId(videoUserId));
        comment.setCommentType(4);
        comment.setUserId(UserHolder.getId());

        Integer countLike = commentService.saveVideoComment(comment);

        //存入缓存
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.VIDEO_LIKE, UserHolder.getId(), videoUserId), "4");


        mqVideoManager.sendVideoMsg(videoUserId, MQVideoManager.VIDEO_LIKE);

        return countLike ;


    }

    //小视频取消点赞
    public Integer dislikeVideo(String videoUserId) {

        Comment comment=new Comment();
        comment.setPublishId(new ObjectId(videoUserId));
        comment.setCommentType(4);
        comment.setUserId(UserHolder.getId());

        Integer countLike = commentService.deleteVideoComment(comment);

        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.VIDEO_LIKE, UserHolder.getId(), videoUserId));

        mqVideoManager.sendVideoMsg(videoUserId, MQVideoManager.VIDEO_DISLIKE);

        return countLike ;


    }

    //小视频发表评论
    public Integer saveVideoComment(String videoUserId, String videoComment) {

        Comment comment=new Comment();
        comment.setPublishId(new ObjectId(videoUserId));
        comment.setCommentType(5);
        comment.setUserId(UserHolder.getId());
        comment.setContent(videoComment);
        comment.setIsParent(true);
        comment.setParentId(new ObjectId(videoUserId));

        Integer countComment = commentService.saveVideoComment(comment);

        mqVideoManager.sendVideoMsg(videoUserId, MQVideoManager.VIDEO_COMMENT);

        return countComment;
    }

    //小视频评论列表
    public PageBeanVo findVideoCommentList(Integer page, Integer pageSize, String videoUserId) {

        PageBeanVo pageBeanVo= commentService.findCommentByVideoId(page,pageSize,videoUserId);

        List<Comment> items = (List<Comment>) pageBeanVo.getItems();
        List<CommentVo> voList=new ArrayList<>();

        if(CollectionUtil.isNotEmpty(items)){
            for (Comment comment : items) {

                CommentVo vo=new CommentVo();

                UserInfo userInfo = userInfoService.findById(comment.getUserId());
                BeanUtil.copyProperties(userInfo,vo);
                vo.setCreateDate(DateFormatUtil.format(new Date(comment.getCreated())));
                vo.setContent(comment.getContent());
                vo.setId(comment.getId().toHexString());
                vo.setLikeCount(comment.getLikeCount());

                String key = StrUtil.format(ConstantUtil.VIDEO_LIKE ,UserHolder.getId(), comment.getId() );
                Boolean flag = stringRedisTemplate.hasKey(key);
                if(flag){ //判断缓存中是否有对某个动态进行了点赞 如果有设置为1
                    vo.setHasLiked(1);
                }
                voList.add(vo);

            }
        }

        pageBeanVo.setItems(voList);
        return pageBeanVo;
    }

    //视频评论点赞
    public Integer videoCommentLike(Long userId, String commentId) {
        //创建对象
        Comment comment=new Comment();
        comment.setPublishId(new ObjectId(commentId));
        comment.setCommentType(6);
        comment.setUserId(userId);

        Integer countLike = commentService.saveCommentLike(comment);

        //存入缓存
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.VIDEO_LIKE, UserHolder.getId(), commentId), "6");
        return countLike;
    }

    //视频评论取消点赞
    public Integer videoCommentNotLike(Long userId, String commentId) {

        Comment comment=new Comment();
        comment.setPublishId(new ObjectId(commentId));
        comment.setCommentType(6);
        comment.setUserId(userId);

        Integer countLike = commentService.deleteCommentLike(comment);

        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.VIDEO_LIKE, UserHolder.getId(), commentId));


        return countLike ;

    }


}
